package com.yifushidai.task;

import com.yifushidai.entity.ApiUniqueMac;
import com.yifushidai.entity.KeypassBandEntity;
import com.yifushidai.entity.OptDeviceLog;
import com.yifushidai.mapper.KeypassBandEntityMapper;
import com.yifushidai.mapper.OptDeviceLogMapper;
import com.yifushidai.utils.CustomPackUtils;
import com.yifushidai.utils.ShisuMinaPushUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class MyRunnable implements Runnable {
    private Logger logger = LoggerFactory.getLogger(MyRunnable.class);

    private KeypassBandEntityMapper keyPassMapper;
    private OptDeviceLogMapper optDeviceLogMapper;
    private ApiUniqueMac one;
    private String temp;
    private Date expireDate;

    public MyRunnable(OptDeviceLogMapper optDeviceLogMapper, KeypassBandEntityMapper keyPassMapper, ApiUniqueMac one, String temp, Date expireDate) {
        this.optDeviceLogMapper = optDeviceLogMapper;
        this.keyPassMapper = keyPassMapper;
        this.one = one;
        this.temp = temp;
        this.expireDate = expireDate;
    }

    @Override
    public void run() {
        try {
            StringBuilder param = new StringBuilder();
            param.append("延时推送临时密码").append(temp).append(" ");
            Object res = ShisuMinaPushUtils.push(one.getMac(), "tempKey:" + temp);
            if ("OK".equals(res)) {
                KeypassBandEntity keypassEntity = keyPassMapper.queryByMac(one.getMac());
                if (keypassEntity == null) return;
                keypassEntity.setTempkey(temp);
                keypassEntity.setTempstatus(CustomPackUtils.OFF_LINE);
                keypassEntity.setUpdateTime(expireDate);
                keyPassMapper.updateByPrimaryKeySelective(keypassEntity);
                optDeviceLogMapper.insertSelective(OptDeviceLog.builder().addressSocket("schedule").mobile(one.getMobile()).uniqueMac(one.getMac()).alias(one.getAddr() + one.getAlias()).optDesc(param.append("任务成功").toString()).build());
            } else {
                optDeviceLogMapper.insertSelective(OptDeviceLog.builder().addressSocket("schedule").mobile(one.getMobile()).uniqueMac(one.getMac()).alias(one.getAddr() + one.getAlias()).optDesc(param.append("任务失败").toString()).build());
            }
        } catch (Exception e1) {
            logger.error(e1.getMessage(), e1);
        }
    }
}
